class Admin::SpusController < AdminController
  def index
    @spus = Spu.all
    if params[:state].presence
      if params[:state] == 'onsale'
        @spus = @spus.where(state: :onsale)
      elsif params[:state] == 'ontrash'
        @spus = @spus.where(state: :ontrash)
      elsif params[:state] == 'oncheck'
        @spus = @spus.where(state: :oncheck)
      elsif params[:state] == 'disagree'
        @spus = @spus.where(state: :disagree)
      end
    end
    if params[:shop_category_id].presence
      @spus = @spus.where(shop_category_id: params[:shop_category_id])
    end
    if params[:handpick].presence
      @spus = @spus.where(handpick: ActiveModel::Type::Boolean.new.cast(params[:handpick]))
    end
    @spus = @spus.order("created_at DESC").page(params[:page]).per(params[:per])
  end
  
  def show
    @spu = Spu.find params[:id]
    @order_items = OrderItem.where(spu_id: @spu.id).order("created_at DESC").page(params[:page]).per(params[:per])
  end

  def edit
    @spu = Spu.find params[:id]
  end

  def update
    @spu = Spu.find params[:id]
    if @spu.update spu_params
      redirect_to admin_spus_path, notice: "审核成功！"
    else
      redirect_to admin_spus_path, notice: "审核失败！"
    end
  end

  def handpick
    @spu = Spu.find params[:id]
    if @spu.update(handpick: !@spu.handpick)
      redirect_to admin_spus_path, notice: "移入严选成功！"
    else
      redirect_to admin_spus_path, notice: "移出严选失败！"
    end
  end

  def show_index
    @spu = Spu.find params[:id]
    if @spu.update(show_index: !@spu.show_index)
      redirect_to admin_spus_path, notice: "移入首页成功！"
    else
      redirect_to admin_spus_path, notice: "移出首页失败！"
    end
  end

  private

  def spu_params
    params.require(:spu).permit(:state, :reason, :handpick, :bonus)
  end
end
